package com.tyylab.kestrel.plugins.nacos.sharens.config.properties;


import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static java.util.Objects.nonNull;

@Configuration
@ConfigurationProperties(prefix = "kestrel.nacos.share")
public class NacosShareProperties {

    private final Map<String, Set<String>> namespace_2_groupname_map = new ConcurrentHashMap<>();

    /**
     * 共享nacos实体列表
     */
    @Getter
    @Setter
    private List<NacosShareEntity> entities;


    public Map<String, Set<String>> getNamespaceGroupMap() {
        if (null!= entities && !entities.isEmpty()) {
            (entities).stream().filter(entity -> nonNull(entity) && nonNull(entity.getNamespace()))
                    .forEach(entity -> {
                        Set<String> groupNames = namespace_2_groupname_map.computeIfAbsent(entity.getNamespace(), k -> new HashSet<>());
                        if (nonNull(entity.getGroupNames()))
                            groupNames.addAll(entity.getGroupNames());
                    });
        }
        return new HashMap<>(namespace_2_groupname_map);
    }

    @Override
    public String toString() {
        return "NacosShareProperties{" +
                "entities=" + entities +
                '}';
    }

    /**
     * 共享nacos实体
     */
    public static final class NacosShareEntity {

        /**
         * 命名空间
         */
        @Getter
        @Setter
        private String namespace;

        /**
         * 分组
         */
        @Getter
        @Setter
        private List<String> groupNames;


        @Override
        public String toString() {
            return "NacosShareEntity{" +
                    "namespace='" + namespace + '\'' +
                    ", groupNames=" + groupNames +
                    '}';
        }
    }
}
